package com.zhou.common.quartz.test.quartz;

import com.zhou.common.quartz.test.quartz.jobclass.MySampleJob;
import com.zhou.common.quartz.test.task.TestAsyncService;
import lombok.RequiredArgsConstructor;
import org.quartz.*;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;

/**
 * @author xianfeng
 * @date 2023/12/20 22:03
 * @description:
 */
@RequiredArgsConstructor
//@Configuration
public class Job2ManualConfig implements ApplicationRunner {

    private static final String ID = "SECOND_JOB";
    private final Scheduler scheduler;

    private final TestAsyncService testAsyncService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        JobDetail jobDetail = JobBuilder.newJob(MySampleJob.class)
                .withIdentity(ID + " 01")
                .usingJobData("name", 1)
                //如何防止作业完成后被删除（ 指示 Quartz 在作业成为“孤儿”时（当作业不再有触发器引用它时）不要删除该作业）
                .storeDurably()
                .build();
        //trigger上的jobdata 会覆盖 jobDetail中的jobData
        // 创建任务触发器
        Trigger trigger = TriggerBuilder.newTrigger()
                .forJob(jobDetail)
                .withIdentity(ID + " 01Trigger")
                .withSchedule(CronScheduleBuilder.cronSchedule("0 0/1 * * * ? *"))
                //corn schedule是不起效果的
                .startNow() //立即執行一次任務
                .usingJobData("name", 2)
                .build();
        // 手动将触发器与任务绑定到调度器内
        scheduler.scheduleJob(jobDetail, trigger);
    }
}
